// Copyright 2019 orivil.com. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found at https://mit-license.org.

package container

import (
	"encoding/json"
	"gitee.com/tugoer/psy-testing/code/models"
	"sync"
)

const sdJsonKey = "sliders"

func readSliderData() (data []byte) {
	return []byte(models.GetJsonData(sdJsonKey))
}

func writeSliderData(data []byte) error {
	return models.SetJsonData(sdJsonKey, string(data))
}

var Sliders = &slider{}

type slider struct {
	data []*models.Slider
	mu   sync.RWMutex
}

var defaultSliders = []*models.Slider{
	{
		Img: "",
		Url: "https://www.baidu.com",
	},
}

func (ec *slider) Save(jsonData string) (err error) {
	ec.mu.Lock()
	defer ec.mu.Unlock()
	var sliders []*models.Slider
	err = json.Unmarshal([]byte(jsonData), &sliders)
	if err != nil {
		return err
	}
	data, err := json.Marshal(sliders)
	if err != nil {
		return err
	}
	err = writeSliderData(data)
	if err != nil {
		return err
	}
	ec.data = sliders
	return nil
}

func (ec *slider) Get() (sliders []*models.Slider, err error) {
	ec.mu.Lock()
	defer ec.mu.Unlock()
	sliders = ec.data
	if sliders == nil {
		// 本地获取数据
		data := readSliderData()
		if len(data) == 0 {
			// 设置默认数据
			sliders = defaultSliders
			data, err := json.Marshal(sliders)
			if err != nil {
				return nil, err
			}
			err = writeSliderData(data)
			if err != nil {
				return nil, err
			}
		} else {
			// 解析本地数据
			err = json.Unmarshal(data, &sliders)
			if err != nil {
				return nil, err
			}
		}
		ec.data = sliders
	}
	return sliders, nil
}
